package common.util;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.lang.UUID;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class PDFCountUtil {
    /**
     * @param directory /home/Sh/
     * @param pdfName   ABC.PDF
     * @return
     * @throws IOException
     */
    public static int getImgSum(String directory, String pdfName) throws IOException {
        cn.hutool.core.lang.UUID uuid = UUID.fastUUID(); // 随机产生唯一的、不可能重复的字符串，用于作为文件夹的名称，使用完后随即给予删除。
        FileUtil.mkdir(directory + uuid);
        FileUtil.copyFile(directory + pdfName, directory + uuid + "/" + pdfName);
        pdfToJpg(directory + uuid + "/", pdfName);
        List<File> jpgList = FileUtil.loopFiles(directory + uuid);
        int i = 0;
        for (File fileJpg : jpgList) {
            String n = fileJpg.getName().toLowerCase().trim(); // 这里的是单文件名称
            if (n.endsWith(".jpg") || n.endsWith(".jpeg") || n.endsWith(".bmp") || n.endsWith(".gif") || n.endsWith(".png")) {
                i++;
            }
        }
        try {
            FileUtil.del(directory + uuid);
        } catch (IORuntimeException e) {
            e.printStackTrace();
        }
        return i;
    }

    public static String pdfToJpg(String directory, String pdfName) throws IOException {
        ProcessBuilder processBuilder = new ProcessBuilder();
        processBuilder.directory(new File(directory));
        processBuilder.command("/usr/local/bin/mutool", "extract", "-r", pdfName); // linux系统下的路径
        //processBuilder.command("D:\\mutool\\mutool.exe", "extract", pdfName);
        processBuilder.redirectErrorStream(true);
        Process process = processBuilder.start();
        InputStream inputStream = process.getInputStream();
        String result = IoUtil.read(inputStream, "utf-8");
        inputStream.close();
        return result;
    }
}
